import * as api from '@/services/article';
import { PlusOutlined, ExclamationCircleFilled } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Drawer, Input, message, Popconfirm, Modal } from 'antd';
import { useRef, useState } from 'react';
import Form from './components/Form';

const ArticleList: React.FC = () => {
  const { confirm } = Modal;

  const [formVisible, setFormVisible] = useState<boolean>(false);
  const [current, setCurrent] = useState<API.ArticleModel | undefined>(undefined);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();

  const [currentRow, setCurrentRow] = useState<API.ArticleModel>();
  const [selectedRowsState, setSelectedRows] = useState<API.ArticleModel[]>([]);

  const handleFormSubmit = async (record: API.ArticleModel) => {
    let result: API.Result;
    const hide = message.loading('正在保存');
    try {
      if (current) {
        result = await api.updateArticle({
          ...current,
          ...record,
        });
      } else {
        result = await api.addArticle({ ...record });
      }
      hide();

      if (result.success) {
        message.success(result.msg);

        setCurrent(undefined);
        setFormVisible(false);
        actionRef.current?.reload();
      } else {
        message.error(result.msg);
      }
    } catch (error) {
      hide();
      message.error('后台异常!');
    }
  };

  const handleRemove = async (id: string) => {
    const result = await api.removeArticle({ ids: id });
    if (result.success) {
      message.success(result.msg);
      actionRef.current?.reload();
    } else {
      message.error(result.msg);
    }
  };

  const handleMoreAction = async () => {
    const result = await api.moreActionArticle();
    if (result.success) {
      message.success(result.msg);
      actionRef.current?.reload();
    } else {
      message.error(result.msg);
    }
  };

  const columns: ProColumns<API.ArticleModel>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      valueType: 'textarea',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '标题',
      dataIndex: 'article_title',
      valueType: 'textarea',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      title: '内容',
      dataIndex: 'article_content',
      valueType: 'textarea',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      title: '创建时间',
      dataIndex: 'create_date',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '修改时间',
      dataIndex: 'modify_date',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (dom, record) => [
        <a
          key="edit"
          onClick={(e) => {
            setFormVisible(true);
            setCurrent(record);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="delete"
          title="确定要删除吗?"
          onConfirm={async () => {
            await handleRemove(record.id);
          }}
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.ArticleModel>
        headerTitle="文章列表"
        columns={columns}
        actionRef={actionRef}
        cardBordered
        request={api.article}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
        editable={{
          type: 'multiple',
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
          defaultValue: {
            option: { fixed: 'right', disable: true },
          },
          onChange(value) {
            //console.log('value: ', value);
          },
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        form={{
          // 由于配置了 transform，提交的参数与定义的不同这里需要转化一下
          syncToUrl: (values, type) => {
            if (type === 'get') {
              return {
                ...values,
                created_at: [values.startTime, values.endTime],
              };
            }
            return values;
          },
        }}
        pagination={{
          pageSize: 10,
          //onChange: (page) => console.log(page),
        }}
        dateFormatter="string"
        toolBarRender={() => [
          <Popconfirm
            key="delete"
            title="确定要测试吗?"
            onConfirm={async () => {
              await handleMoreAction();
            }}
          >
            <Button
              key="button"
              icon={<PlusOutlined />}
              type="primary"
            >
              测试重写多实体
            </Button>
          </Popconfirm>,
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setFormVisible(true);
            }}
            type="primary"
          >
            新建
          </Button>,
        ]}
      />

      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              条
            </div>
          }
        >
          <Button
            key="batchDelete"
            onClick={() => {
              confirm({
                title: '系统提示',
                icon: <ExclamationCircleFilled />,
                content: '确定要批量删除吗?',
                centered: true,
                onOk() {
                  console.log(selectedRowsState);
                  //循环拼接ids，以,分隔
                  let idsArr = new Array();

                  selectedRowsState.forEach((item, index) => {
                    idsArr.push(item.id);
                  });
                  let ids = idsArr.join(',');
                  handleRemove(ids);
                  setSelectedRows([]);
                  actionRef.current?.reloadAndRest?.();
                },
                onCancel() {
                  setSelectedRows([]);
                  actionRef.current?.reloadAndRest?.();
                }
              });
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}

      <Form
        visible={formVisible}
        current={current}
        onSubmit={handleFormSubmit}
        onCancel={() => {
          setFormVisible(false);
          setCurrent(undefined);
        }}
      />

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.id && (
          <ProDescriptions<API.ArticleModel>
            column={2}
            title={currentRow?.id}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.id,
            }}
            columns={columns as ProDescriptionsItemProps<API.ArticleModel>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );

}

export default ArticleList;
